import dayjs from '@/components/dayjs';
import { Ellipsis } from '@/components/Ellipsis';
import ErrorReport from '@/pages/platform/errorReport';
import '@/pages/quality/styles.less';
import { downloadErrorReportFile } from '@/services/platform/errorReport';
import {
  addErrorReport2,
  addWorkHoursRequest,
  finishProductManufactExec,
  getAllErrorPriority,
  getAllErrorType,
  getBomOverview,
  getDrawingInfo,
  getDrawingPreviewUrl,
  getErrorReportByPageAndWo,
  getInspectionTaskValueByProcessId,
  getManufactInfo,
  getProductManufactExecInfosByWoId,
  getProductManufactInforExecuteByPage,
  getProductManufactStateById,
  getSumTimingAndCurStartTime,
  getTeamManufactManager,
  getTeamMember,
  getWorkHoursRequestHstByPageAndTaskId,
  pauseProductManufactExec,
  stagingInspectionTask,
  startProductManufactExec,
  submitInspectionTask,
  updateErrorReport,
  viewBaseInfo,
} from '@/services/product/productManufactInforExecute';
import { filterTranNew, sortTran } from '@/utils/requestUtil';
import { DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import { ModalForm } from '@ant-design/pro-components';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Checkbox,
  Col,
  DatePicker,
  Descriptions,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  notification,
  Radio,
  Row,
  Select,
  Space,
  Spin,
  Table,
  Tabs,
  Upload,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import type {
  DataType,
  recorderrorType,
  recordInfoType,
  tabType,
} from './components/interfaceProduct';
import GuideBookFileInfo from './guideBookFileInfo';
import InspectionFileInfo from './inspectionFileInfo';
import './product.module.less';
import style from './product.module.less';
import './templatestyle.less';
const ProductManufactInforExecute: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const actionRef1 = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [modalVisit2, setModalVisit2] = useState(false); //异常处理终端
  const [modalVisit4, setModalVisit4] = useState(false); //异常处理界面
  const [modalVisit3, setModalVisit3] = useState(false); //异常处理终端
  const [modalVisit5, setModalVisit5] = useState(false); // 工时填报提示框
  const [modalVisit7, setModalVisit7] = useState(false); //pdf预览弹窗
  const [drawingPreview, setdrawingPreview] = useState(''); //pdf预览路径
  const [errorRecord, seterrorRecord] = useState<recorderrorType>();
  const [handlingname, sethandlingname] = useState([]);
  const [formTitle, setFormTitle] = useState('新建');
  const [form] = Form.useForm();
  const [recordInfo, setRecord] = useState<recordInfoType>();
  const [bomTableList, setBOMTableList] = useState();
  const [drawTableList, setDrawTableList] = useState();
  const [stateNumber, setStateNumber] = useState<number>();
  const [manufactInfo, setManufactInfo] = useState();
  const [requestTableList, setrequestTableList] = useState();
  const [pageState, setPageState] = useState('');
  const [ErrorTableList, setErrorTableList] = useState();
  const [confirmLoading2, setConfirmLoading2] = useState(false); //编辑框的disable
  const [confirmLoading5, setConfirmLoading5] = useState(false); //工时填报的disable
  const [formTitle5, setFormTitle5] = useState('工时填报'); //
  const [createOrUpdate5, setCreateOrUpdate5] = useState(false); //工时填报的disable
  const [modalVisit6, setModalVisit6] = useState(false); // 异常填报提示框
  const [confirmLoading6, setConfirmLoading6] = useState(false); //异常填报的disable
  const [formTitle6, setFormTitle6] = useState('生产异常'); //
  const [createOrUpdate6, setCreateOrUpdate6] = useState(false); //异常填报的disable
  const [optionsTask, setoptionsTask] = useState([]); //任务下拉框用到
  const [thewoid, setthewoid] = useState([]);
  const [username, setusername] = useState([]);
  const [managename, setmanagename] = useState([]);
  const [TeamMembername, setTeamMembername] = useState([]);
  const [theerrortype, settheerrortype] = useState([]);
  const [thepriority, setthepriority] = useState([]);
  const [lookForm] = Form.useForm();
  const [lookVisit, setLookVisit] = useState(false);
  const [lookInfo, setLookInfo] = useState<lookInfoType>();
  const dateFormat = 'YYYY-MM-DD';
  const [thetask, setthetask] = useState('');
  const { TextArea } = Input;
  const [file, setFile] = useState();
  const [fileList, setFileList] = useState([]);
  const [thehead, setthehead] = useState([]); //预览用，保存表头
  const [theitem, settheitem] = useState([]); //预览用，保存项
  const [thetitle, setthetitle] = useState('');
  const [thetitleInfo, setTitileInfo] = useState<any>();
  const values: any[] = [];
  const [submit_isnull, setsubmit_isnull] = useState(false); //检验单提交是否存在未填项
  const [accumulatedTime, setAccumulatedTime] = useState(''); //生产工序累计时间
  const ref = useRef(null);
  const [textareamemo, setTextareamemo] = useState('');
  const sequenceArray = ['〇', '①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧']; //工序状态
  const statusWorkInfo = ['待执行', '执行中', '暂停', '完成']; //工序状态
  const [disableState, setDisableState] = useState(false);
  const [calculatingTimeIntervalId, setCalculatingTimeIntervalId] = useState(); //计时器，用于每秒刷新累计时间
  const [errorPreview, setErrorPreview] = useState(''); //存储当前图纸列表的文件预览路径
  const [workOrderInforCode, setWorkOrderInforCode] = useState(''); //生产工序清单id
  const [loadingTime, setLoadingTime] = useState(false); //时间获取加载
  const [loadingFile, setLoadingFile] = useState(false); //文件获取加载
  const [productState, setProductState] = useState(0);
  const [buttonDisabled, setButtonDisabled] = useState(false); //是否禁止点击开启和关闭，防止多次误触
  const [recordItem, setRecordItem] = useState(); //用于存储点击查看的某一项
  const [cumulativeWorkingHours, setCumulativeWorkingHours] = useState('-'); //接线分人员累计工时
  const {
    initialState: {
      currentUser: { name },
    },
  } = useModel('@@initialState');
  type inspectionTaskType = {
    id: string;
    createTime: string;
    createId: string;
    createName: string;
    updateTime: string;
    updateId: string;
    delete: number;
    inspectionTemplateId: string;
    type: string;
    templateName: string;
    processId: null | string;
    projectCode: string;
    infoId: string;
    projectName: string;
    wo: string;
    currentBatch: number;
    batchCount: number;
    state: number;
    finisher: null | string;
    inspector: null | string;
    memo: null | string;
    finishedTime: null | string;
    inspectTime: null | string;
  };

  type lookInfoType = {
    inspectionTask: inspectionTaskType;
    inspectionCostomValueExList: any;
    inspectionItemExList: any;
  };

  type tabsType = {
    key: string;
    name: string;
    label: string;
    content: JSX.Element;
  };
  // 自检清单提交
  const handleSubmit_template = async () => {
    //判断是否有未填项,flase有未填，true每项都填了
    //有填空没有选项
    //有选项没有填空
    //既有选项又有填空
    const isNullArray = theitem.map((item: any, index: any) => {
      const temp = [
        (item.optionType == '单选' || item.optionType == '多选') && item.rightValue == null,
        item.optionType == '填空' && item.descValue == null,
        item.descValue == '',
      ];
      const trueCount = temp.filter((item) => item == true);
      if (trueCount.length >= 1) {
        return true;
      } else {
        return false;
      }
    });
    if (isNullArray.includes(true)) {
      message.warning('检验单有未填项');
    } else {
      const result = await submitInspectionTask({
        inspectionCostomValueDtoList: thehead,
        inspectionItemDtoList: theitem,
        inspectionTask: thetitleInfo,
      });
      if (result && result.code === 0) {
        console.log(theitem, 'inspectionItemDtoList');
        message.success('提交成功');
        setModalVisit(false);
        clearInterval(calculatingTimeIntervalId); //暂停定时器
        setthehead([]);
        settheitem([]);
        setthetitle('');
        setTextareamemo('');
        actionRef.current!.reload();
      }
    }
  };

  //自检清单暂存
  const handleSave_template = async () => {
    const result = await stagingInspectionTask({
      inspectionCostomValueDtoList: thehead,
      inspectionItemDtoList: theitem,
      inspectionTask: thetitleInfo,
    });
    if (result && result.code === 0) {
      message.success('保存成功');
    }
  };

  const keepSubmit = async () => {
    const temp = [];
    lookInfo?.inspectionItemExList.map((item) => {
      temp.push({ id: item.id, value: item.value });
    });
    if (temp.length === 0) {
      setLookVisit(false);
      return;
    }
    const result = await submitInspectionTask({
      inspectionTask: lookInfo?.inspectionTask,
      inspectionItemDtoList: temp,
    });
    lookInfo?.inspectionItemExList.map((item) => {
      item.value = '';
    });
    if (result && result.code === 0) {
      message.success('更新成功');
      actionRef.current!.reload();
    }
    setLookVisit(false);
  };
  const onBlur = (e: any, index: any) => {
    const temp = lookInfo;
    temp.inspectionItemExList[index].value = e.target.value;
    setLookInfo(temp);
  };

  //审核记录信息
  const requestlist: ColumnsType<DataType> = [
    {
      title: '填报人',
      dataIndex: 'requestMan',
      key: 'requestMan',
      align: 'center',
      sorter: true,
    },
    {
      title: '填报时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      sorter: true,
    },
    {
      title: '任务开始时间',
      dataIndex: 'manufactStartDate',
      key: 'manufactStartDate',
      align: 'center',
      sorter: true,
    },
    {
      title: '任务结束时间',
      dataIndex: 'manufactEndDate',
      key: 'manufactEndDate',
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '审批申请号',
    //   dataIndex: 'requestId',
    //   key: 'requestId',
    // },
    {
      title: '标准工时(h)',
      dataIndex: 'standManufactWorkhour',
      key: 'standManufactWorkhou',
      align: 'center',
      sorter: true,
    },
    {
      title: '填报工时(h)',
      dataIndex: 'requestWorkHours',
      key: 'requestWorkHours',
      align: 'center',
      sorter: true,
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      sorter: true,

      render: (text: string, record: any) => {
        return (
          <div>{record.status == 1 ? '待审批' : record.status == 2 ? '审批通过' : '已驳回'}</div>
        );
      },
    },
    {
      title: '审批人',
      // title: '操作人员',
      dataIndex: 'operator',
      key: 'operator',

      align: 'center',
      sorter: true,
    },
    // {
    //   title: '审核描述',
    //   dataIndex: 'approveMemo',
    //   key: 'approveMemo',
    // },
    // {
    //   title: '填报描述',
    //   dataIndex: 'requestMemo',
    //   key: 'requestMemo',
    // },
  ];

  //工时补录页面
  const theitems: tabType[] = [
    {
      name: 'tab1',
      label: `工时补录填报`,
      content: (
        <div style={{ height: 300 }}>
          <Form
            name="wrap"
            labelCol={{ flex: '110px' }}
            labelAlign="right"
            labelWrap
            form={form}
            wrapperCol={{ flex: 1 }}
            colon={false}
          >
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item name="id" label="id" hidden={true}>
                  <Input />
                </Form.Item>
                <Form.Item
                  name="workOrderInforCode"
                  label="工单编号"
                  rules={[{ required: true, message: 'Please input your processCode!' }]}
                >
                  <Input disabled={createOrUpdate5} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="生产任务" name="taskId">
                  <Select
                    // labelInValue
                    placeholder="请选择任务"
                    defaultValue={thetask}
                    onChange={(value) => { }}
                    options={optionsTask}
                    style={{ width: 380 }}
                    disabled
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="任务开始时间"
                  name="manufactStartDate"
                  rules={[{ required: true, message: '请输入开始时间！' }]}
                >
                  <DatePicker style={{ width: 380 }} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="任务结束时间"
                  name="manufactEndDate"
                  rules={[{ required: true, message: '请输入结束时间！' }]}
                >
                  <DatePicker style={{ width: 380 }} />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  name="requestWorkHours"
                  label="补录工时(h)"
                  rules={[{ required: true, message: '请输入补录工时!' }]}
                // hidden={!createOrUpdate}
                >
                  <InputNumber
                    min={0.01}
                    style={{ width: 380 }}
                    addonAfter="h"
                    step="0.01"
                    stringMode
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="requestMan" label="填报人">
                  <Input disabled placeholder="请输入填报人" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={24}>
                <Form.Item
                  name="requestMemo"
                  label="填报描述"
                // rules={[{ required: true, message: '请输入补录工时!' }]}
                >
                  <TextArea rows={3} placeholder="请输入填报描述" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item name="approveMan" label="审核人">
                  <Input disabled placeholder="请输入审核人" />
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <div style={{ textAlign: 'center', float: 'right' }}>
            <Button
              type="primary"
              onClick={() => {
                handleSubmit5();
              }}
            >
              确定
            </Button>
          </div>
        </div>
      ),
    },
    {
      name: 'tab2',
      label: `审核记录`,
      content: (
        <div style={{ height: 500 }}>
          <Table
            columns={requestlist}
            rowKey={(record) => record.id}
            bordered
            dataSource={requestTableList}
            pagination={{ pageSize: 7 }}
          />
        </div>
      ),
    },
  ];

  //BOM清单
  const bomColumns: ColumnsType<DataType> = [
    {
      title: '物料编号',
      dataIndex: 'materialCode',
      key: 'materialCode',
      align: 'center',
      sorter: true,
      ellipsis: true,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      key: 'materialName',
      align: 'center',
      sorter: true,
      ellipsis: true,
    },
    {
      title: '规格',
      dataIndex: 'materialSpec',
      key: 'materialSpec',
      align: 'center',
      sorter: true,
      ellipsis: true,
    },
    {
      title: 'BOM数量',
      dataIndex: 'materialQty',
      key: 'materialQty',
      align: 'center',
      sorter: true,
      render: (text: string, record: any) => {
        return record.materialQty + '/' + record.unit;
      },
      ellipsis: true,
    },
    {
      title: '（安装）位置号',
      dataIndex: 'positionNo',
      key: 'positionNo',
      align: 'center',
      sorter: true,
      ellipsis: true,
      width: 180,
    },
    {
      title: '产品编号',
      dataIndex: 'productCode',
      key: 'productCode',
      align: 'center',
      sorter: true,
      ellipsis: true,
    },
    {
      title: '需求数量',
      dataIndex: 'materialQty',
      key: 'materialQty',
      align: 'center',
      sorter: true,
      ellipsis: true,
    },
    {
      title: '实际数量',
      dataIndex: 'outboundQty',
      key: 'outboundQty',
      align: 'center',
      sorter: true,
      ellipsis: true,
    },
    {
      title: '未领数量',
      dataIndex: 'notIssuedQty',
      key: 'notIssuedQty',
      align: 'center',
      sorter: true,
      render: (text) => {
        let color = 'black-font';
        if (text > 0) {
          color = 'red-font'; //数量大于0 则标为红色
        }
        return <div className={color}>{text}</div>;
      },
      ellipsis: true,
    },
    {
      title: '本次接受数量',
      width: 150,
      dataIndex: 'currentClaimedQty',
      key: 'currentClaimedQty',
      align: 'center',
      sorter: true,
      render: (text: number) => <div>{text}</div>,
      ellipsis: true,

    }
  ];
  //图纸清单
  const drawColumns: ColumnsType<DataType> = [
    {
      title: '图纸类别',
      dataIndex: 'category',
      key: 'category',
      align: 'center',
      sorter: true,
      width: 110,
      ellipsis: true,
    },
    {
      title: '图纸编号',
      dataIndex: 'drawingCode',
      key: 'drawingCode',
      align: 'center',
      sorter: true,
      width: 180,
      ellipsis: true,
    },
    {
      title: '文件名称',
      dataIndex: 'drawingName',
      key: 'drawingName',
      align: 'center',
      sorter: true,
      width: 140,
      ellipsis: true,
      render: (text: string) => {
        return <div>{Ellipsis(text)}</div>;
      },
      ellipsis: true,
    },
    // {
    //   title: '是否打印',
    //   dataIndex: 'printFlag',
    //   key: 'printFlag',
    //   render: (text: string, record: string) => {
    //     return <div>{record?.printFlag == 0 ? '未打印' : '已打印'}</div>;
    //   },
    // },
    {
      title: '状态',
      dataIndex: 'archiveFlag',
      key: 'archiveFlag',
      align: 'center',
      sorter: true,
      render: (text: string, record: any) => {
        return <div>{record!.archiveFlag == 0 ? '使用中' : '已归档'}</div>;
      },
      ellipsis: true,
      width: 80,
    },
    {
      title: '版本号',
      dataIndex: 'version',
      key: 'version',
      align: 'center',
      sorter: true,
      width: 80,
      ellipsis: true,
      render: (text: any) => <span>{'v' + text}</span>,
    },
    {
      title: '上传人',
      dataIndex: 'createName',
      key: 'createName',
      align: 'center',
      sorter: true,
      width: 80,
      ellipsis: true,
    },
    {
      title: '上传时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      sorter: true,
      width: 120,
      ellipsis: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 80,
      align: 'center',
      sorter: true,
      ellipsis: true,
      render: (text, record, _, action) => [
        <a
          key="dowprintKeynloadKey"
          onClick={async () => {
            const result = await getDrawingPreviewUrl(record.id);
            console.log(result);
            if (result.message != undefined) {
              //如果后端传过来的url存在的话，则进行预览
              window.open(result.message);
            } else {
              //如果不存在，则报错
            }
            // const w = window.open('about:blank');
            // w.location.href = record.drawingUrl;
          }}
        >
          预览下载
        </a>,
      ],
    },
  ];
  //工序报表
  const manuColumns: ColumnsType<DataType> = [
    {
      title: '名称',
      dataIndex: 'processName',
      align: 'center',
      sorter: true,
      key: 'processName',
      ellipsis: true,
    },
    {
      title: '柜体编号',
      dataIndex: 'batchProductCode',
      align: 'center',
      width: '200px',
      sorter: true,
      key: 'batchProductCode',
      ellipsis: true,
    },
    {
      title: '柜体类型',
      dataIndex: 'productType',
      align: 'center',
      sorter: true,
      key: 'productType',
      ellipsis: true,
      render: (text) => {
        return <div>{text ? text : '-'}</div>;
      },
    },
    {
      title: '计划开始日期',
      dataIndex: 'planManufactStartDate',
      align: 'center',
      sorter: true,
      ellipsis: true,
      key: 'planManufactStartDate',
    },
    {
      title: '计划结束日期',
      dataIndex: 'planManufactEndDate',
      align: 'center',
      ellipsis: true,
      sorter: true,
      key: 'planManufactEndDate',
    },
    {
      title: '实际开始时间',
      dataIndex: 'manufactStartDate',
      key: 'manufactStartDate',
      align: 'center',
      sorter: true,
      ellipsis: true,
      render: (text) => {
        return <div>{text ? text : '-'}</div>;
      },
    },
    {
      title: '实际结束时间',
      dataIndex: 'manufactEndDate',
      key: 'manufactEndDate',
      align: 'center',
      sorter: true,
      ellipsis: true,
      render: (text) => {
        return <div>{text ? text : '-'}</div>;
      },
    },
    {
      title: '执行时长(m)',
      key: 'manufactDuringDate',
      align: 'center',
      sorter: true,
      ellipsis: true,
      render: (record, text) => {
        if (!record.manufactEndDate && !record.manufactStartDate) {
          return '-';
        }
        if (!record.manufactEndDate) {
          return '-';
        }
        return (
          <div>
            {(
              (new Date(record.manufactEndDate) - new Date(record.manufactStartDate)) /
              1000 /
              60
            ).toFixed(1)}
          </div>
        );
      },
    },
    {
      title: '执行人',
      key: 'operator',
      align: 'center',
      sorter: true,
      ellipsis: true,
      render: () => {
        return <div>{name}</div>;
      },
    },
  ];
  //异常列表
  const errorColumns: ColumnsType<DataType> = [
    {
      title: '异常分类',
      dataIndex: 'errorType',
      key: 'errorType',
      align: 'center',
      sorter: true,
    },
    {
      title: '填报人',
      dataIndex: 'operator',
      key: 'operator',
      align: 'center',
      sorter: true,
    },
    {
      title: '填报时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '问题描述',
    //   dataIndex: 'errorDes',
    //   key: 'errorDes',
    //  align: 'center',sorter: true,
    //   render: (text) => {
    //     return <div>{text ? text : '-'}</div>;
    //   },
    // },
    {
      title: '处理状态',
      dataIndex: 'handleStatus',
      key: 'handleStatus',
      align: 'center',
      sorter: true,
      render: (text: string, record: any) => {
        return (
          <div>
            {record!.handleStatus == 0 ? '未处理' : record!.handleStatus == 1 ? '处理中' : '已完成'}
          </div>
        );
      },
    },
    {
      title: '处理人',
      dataIndex: 'handlingMan',
      key: 'handlingMan',
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '处理描述',
    //   dataIndex: 'handleDes',
    //   key: 'handleDes',
    //  align: 'center',sorter: true,
    //   render: (text) => {
    //     return <div>{text ? text : '-'}</div>;
    //   },
    // },
    {
      title: '处理时间',
      dataIndex: 'handleTime',
      key: 'handleTime',
      align: 'center',
      sorter: true,
      render: (text) => {
        return <div>{text ? text : '-'}</div>;
      },
    },
  ];

  // const handleSubmit_template = async () => {
  //   const result = await submitInspectionTask({
  //     inspectionCostomValueDtoList: thehead,
  //     inspectionItemDtoList: theitem,
  //     inspectionTask: thetitleInfo,
  //   });
  //   if (result && result.code === 0) {
  //     message.success(result.message);
  //   }
  //   actionRef.current!.reload();
  // };

  const handleSubmit = async () => {
    //提交自检清单
    if (pageState === '3') {
      handleSubmit_template();
      // setModalVisit(false);
      // // actionRef.current!.reload();
      // setthehead([]);
      // settheitem([]);
      // setthetitle('');
      actionRef.current!.reload();
    } else {
      actionRef.current!.reload();
      clearInterval(calculatingTimeIntervalId); //暂停定时器
      setModalVisit(false);
    }
  };

  //获取累计时间初试状态
  const getSumTiming = async (id: any, record: any, status: any) => {
    if (status === 0) {
      console.log('工序未开始');
      //未开始
      setAccumulatedTime('生产工序未开始');
    } else if (status === 1) {
      console.log('工序已开始');
      let {
        data: { curStartTime, sumTiming },
      } = await getSumTimingAndCurStartTime(record?.id);
      console.log(curStartTime, sumTiming);
      const interval = setInterval(
        () => getSumTimingByInterval(record, curStartTime, sumTiming),
        500,
      );
      setCalculatingTimeIntervalId(interval);
    } else {
      console.log('工序已暂停或者结束');
      //暂停或者是生产工序结束
      const sumTimeTiming = await getSumTimingAndCurStartTime(id);
      let hours = Number.parseInt(sumTimeTiming.data.sumTiming / 60 / 60);
      let minutes = Number.parseInt((sumTimeTiming.data.sumTiming - hours * 60 * 60) / 60);
      let seconds = sumTimeTiming.data.sumTiming - hours * 60 * 60 - minutes * 60;
      if (hours < 10) {
        hours = '0' + hours;
      }
      if (minutes < 10) {
        minutes = '0' + minutes;
      }
      if (seconds < 10) {
        seconds = '0' + seconds;
      }
      setAccumulatedTime(hours + ':' + minutes + ':' + seconds);
    }
  };
  //统计累计时间
  const getSumTimingByInterval = async (record: any, startTime: any, sumTiming: any) => {
    // console.log('startTime:', startTime, 'sumTiming:', sumTiming);
    // const sumTimeTiming = await getSumTimingAndCurStartTime(id);
    const currentTime = new Date();
    let curStartTime;
    if (!startTime) {
      curStartTime = new Date();
    } else {
      curStartTime = new Date(startTime);
    }
    const timeDifferenceInMilliseconds =
      Number.parseInt((currentTime - curStartTime) / 1000) + sumTiming; //这是累计时间，以秒为单位
    let hours = Number.parseInt(timeDifferenceInMilliseconds / 60 / 60);
    let minutes = Number.parseInt((timeDifferenceInMilliseconds - hours * 60 * 60) / 60);
    let seconds = timeDifferenceInMilliseconds - hours * 60 * 60 - minutes * 60;
    if (hours < 10) {
      hours = '0' + hours;
    }
    if (minutes < 10) {
      minutes = '0' + minutes;
    }
    if (seconds < 10) {
      seconds = '0' + seconds;
    }
    console.log(hours, minutes, seconds);
    setAccumulatedTime(hours + ':' + minutes + ':' + seconds);
  };
  //获取工时工单时间
  const getWorkingHours = async (record: any) => {
    setLoadingTime(true);
    const statetemp = await getProductManufactStateById(record?.id);
    getSumTiming(record.id, record, statetemp.data);
    setLoadingTime(false); //获取累计时间成功，取消加载
  };
  //获取工单工序查看页面的右侧信息
  const getTabsInfo = async (record: any) => {
    setLoadingFile(true);
    setthewoid(record.workOrderInforId);
    /* 获取生产工序编号 */
    setWorkOrderInforCode(record.workOrderInforCode);
    setFormTitle(`查看工单-${record.processName}`);
    setRecord(record);
    setStateNumber(record.processStatus);
    try {
      const [BOMListResult, drawList, manufactInfoTemp, template, statetemp] = await Promise.all([
        getBomOverview(record.workOrderInforId),
        getDrawingInfo(record.workOrderInforId),
        getManufactInfo(record.workOrderInforId),
        getInspectionTaskValueByProcessId(record.id),
        getProductManufactStateById(record?.id),
      ]);
      console.log('并行请求结果：', BOMListResult, drawList, manufactInfoTemp, template, statetemp);
      setBOMTableList(BOMListResult?.data); //获取BOM清单
      setDrawTableList(drawList?.data); //获取图纸
      if (manufactInfoTemp != undefined) {
        manufactInfoTemp?.data?.map((item: any) => {
          item.key = item.id;
        });
      }
      setManufactInfo(manufactInfoTemp?.data); //获取进度
      if (template != undefined) {
        if (template.message == '没有自检单') {
        } else {
          setTitileInfo(template.data.inspectionTask);
          setthetitle(template.data.inspectionTask?.templateName);
          setthehead(template.data.inspectionCostomValueExList);
          settheitem(template.data.inspectionItemExList);
          setTextareamemo(template.data.inspectionTask.memo);
        }
      }
      // console.log(111);
      setLoadingFile(false); //获取其他资料成功，取消加载
      setProductState(statetemp.data);
    } catch (error) {
      notification.error({
        message: '获取数据失败！',
        description: { error },
      });
      // setLoadingTime(false); //获取累计时间成功，取消加载
      setLoadingFile(false); //获取其他资料成功，取消加载
    }
  };
  const getCumulativeWorkingHours = (record: any, state: number) => {
    console.log(record, state, statusWorkInfo[record.processStatus]);
    if (statusWorkInfo[record.processStatus] === '完成') {
      const time = (new Date(record.manufactEndDate) - new Date(record.manufactStartDate)) / 1000;
      const DD = parseInt(time / 60 / 60 / 24);
      const HH = parseInt(time / 60 / 60) - DD * 24;
      const mm = parseInt(time / 60) - DD * 24 * 60 - HH * 60;
      const ss = parseInt(time) - DD * 24 * 60 * 60 - HH * 60 * 60 - mm * 60;
      console.log(DD, HH, mm, ss);
      setCumulativeWorkingHours(DD + '-' + HH + ':' + mm + ':' + ss);
    } else {
      setCumulativeWorkingHours('工序未結束');
    }
  };
  const columns: ProColumns[] = [
    {
      title: '工单id',
      dataIndex: 'workOrderInforId',
      key: 'workOrderInforId',
      search: false,

      hideInTable: true,
    },
    {
      title: '工单编号',
      dataIndex: 'workOrderInforCode',
      align: 'center',
      sorter: true,
      width: 180,

      key: 'workOrderInforCode',
    },
    {
      title: '柜体编号',
      dataIndex: 'batchProductCode',
      key: 'batchProductCode',
      width: 180,

      align: 'center',
      sorter: true,
    },
    {
      title: '工序',
      dataIndex: 'processName',
      key: 'processName',
      search: false,
      align: 'center',
      sorter: true,
      // render: (dom, entity) => {
      //   return (
      //     <div>
      //       {entity.processName} : {entity.workOrderInforCode}-{entity.sequence}
      //     </div>
      //   );
      // },
    },
    {
      title: '生产工序',
      dataIndex: 'isProductionProcess',
      key: 'isProductionProcess',
      search: false,
      align: 'center',
      sorter: true,
      width: 100,
      render: (text) => <span>{text === 1 ? '是' : '否'}</span>,
    },
    {
      title: '工序顺序',
      dataIndex: 'sequence',
      align: 'center',
      sorter: true,
      search: false,
      key: 'sequence',
      /* render: (text) => {
        return <div>{sequenceArray[Number(text)]}</div>;
      }, */
    },
    {
      // 这里将来要设置成颜色
      title: '工序状态',
      dataIndex: 'alertStatus',
      key: 'AlertStatus',

      search: false,
      align: 'center',
      sorter: true,
      render: (text) => {
        let color = 'red-retangle base-retangle';
        if (text === 1) {
          color = 'green-retangle base-retangle';
        } else if (text === 2) {
          color = 'yellow-retangle base-retangle';
        } else if (text === 3) {
          color = 'black-retangle base-retangle';
        } else if (text === 4) {
          color = 'purple-retangle base-retangle';
        } else if (text === 5) {
          color = 'red-retangle base-retangle';
        } else {
          color = 'white-retangle base-retangle';
        }
        return <div className={color} />;
      },
    },
    // {
    //   title: '工序计划周期',
    //   dataIndex: 'workOrderInforCode',
    //   key: 'workOrderInforCode',
    //  align: 'center',sorter: true,
    //   render: (text, record) => {
    //     return (
    //       <React.Fragment>
    //         {record.planManufactStartDate}~{record.planManufactEndDate}
    //       </React.Fragment>
    //     );
    //   },
    // },
    {
      title: '计划开始',
      dataIndex: 'planManufactStartDate',
      key: 'planManufactStartDate',
      search: false,
      align: 'center',
      sorter: true,
    },
    {
      title: '计划结束',
      dataIndex: 'planManufactEndDate',
      key: 'planManufactEndDate',
      search: false,
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '实际完成周期',
    //   dataIndex: 'sequence',
    //   key: 'sequence',
    //  align: 'center',sorter: true,
    //   render: (text, record) => {
    //     return (
    //       <div>
    //         {record.manufactStartDate}~{record.manufactEndDate}
    //       </div>
    //     );
    //   },
    // },
    {
      title: '实际开始',
      dataIndex: 'manufactStartDate',
      key: 'manufactStartDate',
      search: false,

      width: 180,
      align: 'center',
      sorter: true,
    },
    {
      title: '实际结束',
      dataIndex: 'manufactEndDate',
      key: 'manufactEndDate',
      search: false,
      width: 180,
      align: 'center',
      sorter: true,
    },

    {
      title: '实际工时(h)',
      dataIndex: 'manufactWorkhour',
      search: false,
      key: 'manufactWorkhour',

      align: 'center',
      // sorter: true,
      render: (text, record) => {
        return <div>{record.manufactWorkhour ? record.manufactWorkhour.toFixed(2) : '0.00'}</div>;
      },
    },
    {
      title: '标准工时(h)',
      dataIndex: 'standManufactWorkhour',
      key: 'standManufactWorkhour',
      search: false,

      align: 'center',
      sorter: true,
      render: (text, record) => {
        return <div>{record.standManufactWorkhour.toFixed(2)}</div>;
      },
    },
    {
      title: '状态',
      dataIndex: 'processStatus',
      key: 'processStatus',
      search: false,

      align: 'center',
      sorter: true,
      render: (text, record) => {
        return <div>{statusWorkInfo[record.processStatus]}</div>;
      },
    },
    {
      title: '备注',
      dataIndex: 'memo',
      key: 'memo',

      search: false,
      align: 'center',
      sorter: true,
      hideInTable: true, //隐藏备注
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      search: false,
      width: 180,
      render: (text, record) => [
        <a
          key="editKey"
          onClick={async () => {
            setModalVisit(true);
            setRecordItem(record);
            getCumulativeWorkingHours(record);
            await getWorkingHours(record);
            await getTabsInfo(record);
            // const BOMListResult = await getBomOverview(record.workOrderInforId);//获取bom列表
            // const drawList = await getDrawingInfo(record.workOrderInforId);//获取图纸列表
            // const manufactInfoTemp = await getManufactInfo(record.workOrderInforId); //获取进度
            // const template = await getInspectionTaskValueByProcessId(record.id); // 获取自检清单
          }}
        >
          查看
        </a>,
        <a
          key="addwoKey"
          disabled={record.processStatus != 3}
          onClick={async () => {
            if (record.processStatus != 3) {
              message.warning('当前工序尚未完成，不能进行补录');
            } else {
              // 获取生产经理
              const getteammanage = await getTeamManufactManager(record.workOrderInforId);
              setmanagename(getteammanage.data?.name);
              if (getteammanage.data?.name == undefined) {
                message.warning('请先添加生产经理');
              }
              // 获取填报人
              const getuserlist = await viewBaseInfo(null);
              // 获取审核记录
              const requestParams = {
                taskId: record.id,
                pageEntity: {
                  current: 1,
                  filters: [],
                  pageSize: 1000,
                  sorters: [],
                },
              };
              const requestList = await getWorkHoursRequestHstByPageAndTaskId(requestParams);
              setrequestTableList(requestList.data.content); //获取审核列表
              // 获取任务
              const tasklabel =
                record.processName + ':' + record.workOrderInforCode + '-' + record.sequence;
              setthetask(tasklabel);
              setModalVisit5(true);
              setCreateOrUpdate5(true);
              setFormTitle5('工时补录');
              form.setFieldsValue({
                workOrderInforCode: record.workOrderInforCode,
                workOrderInforId: record.workOrderInforId,
                requestWorkHours: 0.0,
                manufactStartDate:
                  record.manufactStartDate == undefined
                    ? record.manufactStartDate
                    : dayjs(record.manufactStartDate, dateFormat),
                manufactEndDate:
                  record.manufactEndDate == undefined
                    ? record.manufactEndDate
                    : dayjs(record.manufactEndDate, dateFormat),
                requestMan: getuserlist.data.name,
                approveMan: getteammanage.data?.name,
              });
              setthewoid(record.workOrderInforId);
              setRecord(record);
              // 获取任务下拉框内容
              const gettasklist = await getProductManufactExecInfosByWoId(record.workOrderInforId);
              const taskOptionContract = [];
              gettasklist.data.map((item: any, index: any) => {
                taskOptionContract.push({ value: item.taskId, label: item.task });
              });
              setoptionsTask(taskOptionContract);
            }
          }}
        >
          工时补录
        </a>,
      ],
    },
  ];

  /**开始计时 */
  const startWorkOrder = async () => {
    setButtonDisabled(true);
    let result;
    if (productState === 0 || productState === 2) {
      //开始生产工序
      result = await startProductManufactExec(recordInfo?.id);
      const statetemp = await getProductManufactStateById(recordInfo?.id);
      if (statetemp && statetemp.data) {
        setProductState(statetemp.data);
        const sumTimeTiming = await getSumTimingAndCurStartTime(recordInfo?.id);
        const startTime = new Date(sumTimeTiming.data.curStartTime);
        const sumTiming = sumTimeTiming.data.sumTiming;
        console.log(startTime, sumTiming);
        const interval = setInterval(
          () => getSumTimingByInterval(recordInfo, startTime, sumTiming),
          500,
        );
        setCalculatingTimeIntervalId(interval);
      }
      if (result && result.code === 0) {
        message.success('工序开始计时');
        setButtonDisabled(false);
      }
    } else if (productState === 1) {
      //暂停生产工序
      clearInterval(calculatingTimeIntervalId); //暂停定时器
      result = await pauseProductManufactExec(recordInfo?.id);
      const statetemp = await getProductManufactStateById(recordInfo?.id);
      if (statetemp && statetemp.data) {
        setProductState(statetemp.data);
        // getSumTiming(recordInfo.id, recordInfo, statetemp.data);
      }
      if (result && result.code === 0) {
        message.success('工序暂停计时');
        setButtonDisabled(false);
      }
    }
    // 重新获取自检清单
    const template = await getInspectionTaskValueByProcessId(recordInfo?.id);
    if (template != undefined) {
      if (template.message == '没有自检单') {
      } else {
        setTitileInfo(template.data.inspectionTask);
        setthetitle(template.data.inspectionTask?.templateName);
        setthehead(template.data.inspectionCostomValueExList);
        settheitem(template.data.inspectionItemExList);
      }
    }
    setButtonDisabled(false);
  };

  //节流函数，公式工序暂停运行防止多次点击
  const throttle = function (func, delay) {
    let timer = 0;
    return async function () {
      const now = Date.now();
      console.log(now - timer);
      if (now - timer >= delay) {
        timer = now;
        await func();
        console.log('这个函数被执行了');
      }
    };
  };
  //生成新的节流函数
  const startWorkOrderThrottled = throttle(startWorkOrder, 2000);
  /**完成 */
  const finishWorkOrder = async () => {
    const result = await finishProductManufactExec(recordInfo?.id);
    console.log(
      result,
      result?.code,
      result?.code === 0,
      result && result?.code && result?.code === 0,
    );
    if (result !== undefined && result.code === 0) {
      message.success(result.message);
      clearInterval(calculatingTimeIntervalId); //暂停定时器
      const statetemp = await getProductManufactStateById(recordInfo?.id);
      console.log(statetemp, result);
      //获取工序分线人员累计工时
      if (statetemp && statetemp.data) {
        setProductState(statetemp.data);
        // getSumTiming(recordInfo.id, recordInfo, recordInfo.processStatus);
        // getSumTimingByInterval(recordInfo?.id, recordInfo);
      }
    }
    setModalVisit(false);
    actionRef.current?.reload();
    setButtonDisabled(false);
  };
  /* 获取当前点击图纸点击列表的pdf或者图片的预览路径 */
  const getErrorPreview = async (record: any) => {
    const errorPreviewUrl = await getErrorPreviewUrl(record);
  };
  const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
    console.log(current, pageSize);
  };

  //定义Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: 'BOM清单',
      content: (
        <div style={{ height: 500 }}>
          <Table
            columns={bomColumns}
            rowKey={(record) => record.id}
            bordered
            loading={loadingFile}
            dataSource={bomTableList}
            pagination={{
              defaultPageSize: 100,
              defaultCurrent: 1,
              pageSizeOptions: [100, 500, 1000],
              showSizeChanger: true,
            }}
            scroll={{ x: 1400, y: 400 }}
          />
        </div>
      ),
    },
    {
      name: 'tab2',
      label: '图纸列表',
      content: (
        <div style={{ height: 500 }}>
          <Table
            columns={drawColumns}
            bordered
            loading={loadingFile}
            rowKey={(record) => record.id}
            // onRow={(record) => (onclick = () => {})}
            dataSource={drawTableList}
            pagination={{
              defaultPageSize: 100,
              defaultCurrent: 1,
              pageSizeOptions: [100, 500, 1000],
              showSizeChanger: true,
            }}
          />
        </div>
      ),
    },
    {
      name: 'tab3',
      label: '工序报表',
      content: (
        <div style={{ height: 500 }}>
          <Table
            columns={manuColumns}
            scroll={{ x: 1500 }}
            bordered
            loading={loadingFile}
            dataSource={manufactInfo}
            pagination={{
              defaultPageSize: 100,
              defaultCurrent: 1,
              pageSizeOptions: [100, 500, 1000],
              showSizeChanger: true,
            }}
          />
        </div>
      ),
    },
    {
      name: 'tab4',
      label: '自检清单',
      content: (
        <div style={{ height: 500, whiteSpace: 'nowrap' }}>
          {' '}
          {/*使得第一行不换行 */}
          {/* 模板预览 */}
          <div className="templatebox">
            <div className="pdName">{thetitle == '' ? '暂时没有工序检验表' : thetitle}</div>
            <div className="company" hidden={thetitle == ''}>
              <div className="company_name">电柜管家</div>
              <div className="triangle" />
              <ul className="title_list">
                {thehead?.map((item, index) => {
                  return <li key={index}>{item?.name + ':' + item?.templateCustomItemValue}</li>;
                })}
              </ul>
            </div>
            <ul className="list" disabled={stateNumber == 3}>
              {theitem?.map((item, index) => {
                if (item?.optionType == '单选') {
                  const selectOption = item?.rightOption.split('|');
                  if (item?.isDetailDes == '1') {
                    //有描述框
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                          <div className="templatecontent">
                            <Input
                              disabled={stateNumber == 3}
                              className="detailinput"
                              defaultValue={item.descValue}
                              value={values[item.sortId]}
                              onChange={(e) => {
                                values[item.sortId] = e.target.value;
                                item.descValue = e.target.value;
                              }}
                              placeholder={'请输入描述内容'}
                            />
                          </div>
                        </div>
                        <div className="radio_wrapper">
                          <Radio.Group
                            disabled={stateNumber == 3}
                            options={selectOption}
                            defaultValue={item.rightValue}
                            onChange={(e) => {
                              item.rightValue = e.target.value;
                            }}
                          />
                        </div>
                      </li>
                    );
                  } else {
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                        </div>
                        <div className="radio_wrapper">
                          <Radio.Group
                            disabled={stateNumber == 3}
                            options={selectOption}
                            defaultValue={item.rightValue}
                            onChange={(e) => {
                              item.rightValue = e.target.value;
                            }}
                          />
                        </div>
                      </li>
                    );
                  }
                } else if (item?.optionType == '多选') {
                  const thedescOption = item?.descOption.split('|');
                  if (item?.isExtendDes == '1') {
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                          <div className="templatecontent">
                            <Checkbox.Group
                              disabled={stateNumber == 3}
                              options={thedescOption}
                              defaultValue={item.multiValue}
                              onChange={(e) => {
                                item.multiValue = e.target.value;
                              }}
                            />
                            <div className="other">
                              <div>
                                <span>*</span>如果没有合适选项，请文字描述:
                              </div>
                              <Input
                                disabled={stateNumber == 3}
                                className="detailinput"
                                defaultValue={item.multiDesValue}
                                value={values[item.sortId]}
                                onChange={(e) => {
                                  values[item.sortId] = e.target.value;
                                  item.multiDesValue = e.target.value;
                                }}
                                placeholder={'请输入描述内容'}
                              />
                            </div>
                          </div>
                        </div>
                      </li>
                    );
                  } else {
                    return (
                      <li key={index} className="list_item">
                        <div className="question_wrapper">
                          <div className="title">
                            {index + 1}|{item?.itemName}
                            {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                              ? ':（' + item?.inspectionMethod + '）'
                              : ''}
                          </div>
                          <div className="templatecontent">
                            <Checkbox.Group
                              disabled={stateNumber == 3}
                              options={thedescOption}
                              defaultValue={item.multiValue}
                              onChange={(e) => {
                                item.multiValue = e.target.value;
                              }}
                            />
                          </div>
                        </div>
                      </li>
                    );
                  }
                } else if (item?.optionType == '描述') {
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                        <div className="templatecontent">
                          <TextArea
                            disabled={stateNumber == 3}
                            rows={3}
                            className="detailinput"
                            placeholder={'请输入描述内容'}
                            defaultValue={item.descValue}
                            value={values[item.sortId]}
                            onChange={(e) => {
                              values[item.sortId] = e.target.value;
                              item.descValue = e.target.value;
                            }}
                          />
                        </div>
                      </div>
                    </li>
                  );
                } else {
                  return (
                    <li key={index} className="list_item">
                      <div className="question_wrapper">
                        <div className="title">
                          {index + 1}|{item?.itemName}
                          {item?.inspectionMethod != undefined && item?.inspectionMethod != ''
                            ? ':（' + item?.inspectionMethod + '）'
                            : ''}
                        </div>
                        <div className="templatecontent">
                          <Input
                            className="detailinput"
                            placeholder={'请输入填空内容'}
                            defaultValue={item.descValue}
                            value={values[item.sortId]}
                            onChange={(e) => {
                              values[item.sortId] = e.target.value;
                              item.descValue = e.target.value;
                            }}
                          />
                        </div>
                      </div>
                    </li>
                  );
                }
              })}
            </ul>
            {thetitle !== '' ? (
              <div>
                <span style={{ marginTop: '40px' }}>备注：</span>
                <Input
                  disabled={stateNumber == 3}
                  className="textareamemo"
                  placeholder={'请输入备注内容'}
                  // defaultValue={item.memo}
                  value={textareamemo}
                  onChange={(e) => {
                    // values[item.sortId] = e.target.value;
                    // item.memo = e.target.value;
                    setTextareamemo(e.target.value);
                    thetitleInfo.memo = e.target.value;
                  }}
                />
              </div>
            ) : (
              ''
            )}
            <hr />
            <div style={{ width: 770, textAlign: 'center' }}>
              <Button
                type="primary"
                hidden={thetitle == ''}
                onClick={() => {
                  handleSave_template();
                }}
              >
                保存
              </Button>
              <Button
                style={{ marginLeft: '20px' }}
                type="primary"
                hidden={thetitle == ''}
                onClick={() => {
                  handleSubmit_template();
                }}
              >
                提交
              </Button>
            </div>
          </div>
        </div>
      ),
    },
    {
      name: 'tab5',
      label: '自检附件',
      content: (
        <div style={{ height: 500 }}>
          <InspectionFileInfo theid={recordInfo?.id} thestate={recordInfo?.processStatus} />
        </div>
      ),
    },
    {
      name: 'tab6',
      label: '异常列表',
      content: (
        <div style={{ height: 500 }}>
          {/* <Table
            columns={errorColumns}
            bordered
            rowKey={(record) => record.id}
            pagination={false}
            dataSource={ErrorTableList}
            onRow={(record) => ({
              onClick: () => {
                seterrorRecord(record);
                setModalVisit4(true);
                // history.push('/platform/errorReport');
                // setModalVisit3(true);
                sethandlingname(record.handlingMan);
                console.log(errorRecord);
                console.log(record);
              },
            })}
          /> */}
          <ProTable
            actionRef={actionRef1} //用于触发刷新操作等，看api
            formRef={ref}
            rowKey="id"
            search={false}
            onRow={(record) => ({
              onClick: () => {
                seterrorRecord(record);
                setModalVisit4(true);
                sethandlingname(record.handlingMan);
              },
            })}
            request={async () => {
              const errorParams = {
                wo: workOrderInforCode,
                pageEntity: {
                  current: 1,
                  filters: [],
                  pageSize: 6,
                  sorters: [],
                },
              };
              const ErrorList = await getErrorReportByPageAndWo(errorParams);

              setErrorTableList(ErrorList.data.content); //获取异常列表
              return {
                data: ErrorList.data.content,
                success: ErrorList.message,
                total: ErrorList.data.totalElements,
              };
            }}
            columns={errorColumns}
            scroll={{ x: 1200, y: 300 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
    {
      name: 'tab7',
      label: '工艺指导书',
      content: (
        <div>
          <GuideBookFileInfo theid={recordInfo?.id} batchproductid={recordInfo?.batchProductId} />
        </div>
      ),
    },
  ];

  //获取：用户名（填报人）
  const getuser = async () => {
    const getuserlist = await viewBaseInfo(null);
    setusername(getuserlist.data.name);
  };

  // 获取下拉框内容
  const getselect = async () => {
    // 异常类型
    const geterrortype = await getAllErrorType(null);
    const errortypeOptionContract = [];
    geterrortype.data.map((item: any, index: any) => {
      errortypeOptionContract.push({ value: item.errorType, label: item.errorType });
    });
    settheerrortype(errortypeOptionContract);
    // 异常优先级
    const getpriority = await getAllErrorPriority(null);
    const priorityOptionContract = [];
    getpriority.data.map((item: any, index: any) => {
      priorityOptionContract.push({ value: item.priority, label: item.priorityDes });
    });
    setthepriority(priorityOptionContract);
  };

  // 工时补录
  const handleSubmit5 = async () => {
    setConfirmLoading5(true);
    form
      .validateFields()
      .then(async () => {
        const res = form.getFieldsValue();
        // 判断开始结束时间是否跨月
        const enddata = dayjs(res.manufactEndDate).format('MM');
        const startdata = dayjs(res.manufactStartDate).format('MM');
        if (enddata != startdata) {
          message.warning('工序的开始和结束时间不能跨月');
          setConfirmLoading5(false);
        } else if (res.requestWorkHours == 0) {
          message.warning('工时不能为0');
        } else {
          res.requestWorkHours = parseFloat(res.requestWorkHours).toFixed(2);
          res.manufactEndDate = dayjs(res.manufactEndDate).format(dateFormat);
          res.manufactStartDate = dayjs(res.manufactStartDate).format(dateFormat);
          // res.requestMan = username;
          // res.approveMan = managename;
          res.workOrderInforId = thewoid;
          res.wo = recordInfo?.workOrderInforCode;
          res.taskId = recordInfo?.id;
          const result = await addWorkHoursRequest(res);
          if (result != null) {
            message.success('工时填报成功');
          }
          setConfirmLoading5(false);
          setModalVisit5(false);
          actionRef.current!.reload();
        }
      })
      .catch(() => {
        setConfirmLoading5(false);
      });
  };
  // 异常填报提交
  const add_error = async () => {
    setConfirmLoading6(true);
    form
      .validateFields()
      .then(async () => {
        const res = form.getFieldsValue();
        const formData = new window.FormData();
        fileList?.map((item: any) => {
          formData.append('file', item.originFileObj); //需要将file类型的文件转入formData中，不然后端接收不到
        });
        res.file = formData;
        res.deadLine = dayjs(res.deadLinetime).format(dateFormat);
        res.operator = username;
        res.Wo = recordInfo?.workOrderInforCode;
        res.workOrderInforId = recordInfo?.workOrderInforId;
        res.taskId = recordInfo?.id;
        const result = await addErrorReport2(res);
        if (result != null) {
          message.success('异常新增成功');
        }
        setConfirmLoading6(false);
        setModalVisit6(false);
        actionRef.current!.reload();
        actionRef1.current!.reload();
      })
      .catch(() => {
        setConfirmLoading6(false);
        // actionRef1.current!.reload();
      });
  };

  //去处理
  const dealwith = async () => {
    form
      .validateFields()
      .then(async () => {
        const res = { ...form.getFieldsValue() };
        errorRecord.handleDes = res.handleDes;
        const errorReportDto = errorRecord;
        errorReportDto.handleStatus = '1';
        const currentTime =
          new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate();
        errorReportDto.handleTime = currentTime;
        const result = await updateErrorReport(errorReportDto);
        if (result != null) {
          message.success('处理成功');
          form.resetFields();
        }
        setConfirmLoading2(false);
        setModalVisit2(false);
        actionRef.current.reload();
      })
      .catch(() => {
        setConfirmLoading2(false);
      });
  };
  const onFilesChange = (info: any, event: any) => {
    console.log('info:', info);
    console.log('event', event);

    // setFileList(info.fileList);
  };

  /* 在文件上传之前进行检验 */
  const handleBeforeUpload = (info: any) => {
    // console.log('在文件上传之前进行检验', info);
    //检验文件大小
    // if (info.size) {
    //   const isLt = info.size / 1024 / 1024 < 1000;
    //   if (!isLt) {
    //     alert(`上传文件大小不能超过 ${1} GB!`);
    //     return false;
    //   } else {
    //     //验证通过
    //   }
    // }
    //检验成功
    return false; //这里必须要返回false，来阻止原生的组件的默认action行为，不然会显示存储错误的信息
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="生产执行查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        // search={false}
        toolBarRender={(action, { selectedRows }) => [
          <div className="projectScheduleGroup">
            <span>待执行：</span>
            <img src="../wks.gif" />
            <span>执行中：</span>
            <img src="../zxz.gif" />
            <span>暂停：</span>
            <img src="../zt.gif" />
            <span>结束：</span>
            <img src="../wc.gif" />
            <span>未按计划开始：</span>
            <img src="../purple.png" />
            <span>未按计划结束：</span>
            <img src="../red.png" />
          </div>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTranNew(params);
          const result = await getProductManufactInforExecuteByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });

          getuser();
          getselect();
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        // scroll={{ x: 2000, y: 350 }}
        scroll={{ x: 2000, y: 'calc(100vh - 400px)' }}
        rowSelection={{}}
        pagination={{
          pageSize: 100,
          pageSizeOptions: [100, 500, 1000],
        }}
      />

      {/* 查看工单弹窗 */}
      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        width={1500}
        submitter={false}
        modalProps={{
          footer: null,
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
            setAccumulatedTime('');
            clearInterval(calculatingTimeIntervalId);
            setthehead([]);
            settheitem([]);
            setthetitle('');
            actionRef.current!.reload();
          },
        }}
      >
        <div className={style.box}>
          <div className={style.left}>
            <div style={{ fontSize: '20px', fontWeight: '600' }}>工单</div>
            <span>{recordInfo ? recordInfo?.workOrderInforCode : ''}</span>
            <hr />
            <div className={style.bottom}>
              <div className={style.statusStyle}>
                <div style={{ fontSize: '16px', fontWeight: '600' }}>状态</div>
                <div>
                  {statusWorkInfo[Number(stateNumber)]
                    ? statusWorkInfo[Number(stateNumber)]
                    : '***'}
                </div>
              </div>
              <div className={style.accumulatedTimeStyle}>
                <div style={{ fontSize: '16px', fontWeight: '600' }}>累计时间</div>
                <div
                  style={{
                    width: '100%',
                    height: '30px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    // textAlign: 'right',
                  }}
                >
                  <Spin spinning={loadingTime} size="small">
                    <span>{accumulatedTime}</span>
                  </Spin>
                </div>
              </div>
            </div>
            <hr />
            <div className={style.personnelTimeStyle}>
              <span style={{ fontSize: '16px', fontWeight: '600' }}>工序分人员累计工时</span>
              <span>{cumulativeWorkingHours}</span>
              {/* todo */}
            </div>
            <hr />
            <div className={style.row}>
              <Button
                type="primary"
                disabled={[3].includes(Number(productState)) || buttonDisabled}
                onClick={startWorkOrder}
              >
                {[0, 2, 3].includes(Number(productState)) ? '开始' : '暂停'}
              </Button>
            </div>
            <div className={style.row}>
              <Button
                type="primary"
                disabled={[0, 3].includes(Number(productState))}
                onClick={finishWorkOrder}
              >
                完成
              </Button>
            </div>
            <div className={style.row}>
              <Button
                type="primary"
                onClick={async () => {
                  // 获取任务
                  const tasklabel =
                    recordInfo?.processName +
                    ':' +
                    recordInfo?.workOrderInforCode +
                    '-' +
                    recordInfo?.sequence;
                  // 获取任务下拉框内容
                  const gettasklist = await getProductManufactExecInfosByWoId(
                    recordInfo?.workOrderInforId,
                  );
                  const taskOptionContract = [];
                  gettasklist?.data?.map((item: any, index: any) => {
                    taskOptionContract.push({ value: item.taskId, label: item.task });
                  });
                  setoptionsTask(taskOptionContract);
                  // 获取项目团队成员
                  const getmember = await getTeamMember(recordInfo?.workOrderInforId);
                  const member = [];
                  getmember?.data.map((item: any, index: any) => {
                    if (item) {
                      member.push({ value: item.name, label: item.name });
                    }
                  });
                  setTeamMembername(member);
                  setthetask(tasklabel);
                  setModalVisit6(true);
                  setCreateOrUpdate6(true);
                  setFormTitle6('生产异常');
                  form.setFieldsValue({
                    workOrderInforCode: recordInfo?.workOrderInforCode,
                    workOrderInforId: recordInfo?.workOrderInforId,
                    id: recordInfo?.id,
                    // taskId: recordInfo?.taskId,
                    errorDes: '',
                    deadLinetime: '',
                    priority: '',
                    handlingMan: '',
                    errorType: '',
                    file: '',
                  });
                }}
              >
                异常填报
              </Button>
            </div>
          </div>
          <div className={`${style.right}`}>
            <Tabs
              destroyInactiveTabPane //每次切换tabs的时候销毁DOM,以此达到刷新的效果，但是这种方式比较消耗性能
              type="card"
              onChange={(e) => {
                setPageState(String(Number(e) - 1));
                getTabsInfo(recordItem); //更新一下数据
              }}
              defaultActiveKey="0"
              items={tabList.map((item, i) => {
                const id = String(i + 1);
                return {
                  label: item.label,
                  key: id,
                  children: <div>{item.content}</div>,
                };
              })}
            />
          </div>
        </div>
      </ModalForm>
      <Modal
        title="工时补录"
        width={1100}
        open={modalVisit5}
        onOk={() => setModalVisit5(false)}
        onCancel={() => {
          setModalVisit5(false);
          actionRef.current?.reload();
        }}
        footer={null}
      >
        <Tabs
          // defaultActiveKey="0"
          destroyInactiveTabPane //每次切换tabs的时候销毁DOM,以此达到刷新的效果，但是这种方式比较消耗性能
          items={theitems.map((item, i) => {
            const id = String(i + 1);
            return {
              label: item.label,
              key: id,
              children: <div>{item.content}</div>,
            };
          })}
        // onChange={onChange}
        />
      </Modal>
      <Modal
        title={formTitle6}
        visible={modalVisit6}
        onOk={add_error}
        confirmLoading={confirmLoading6}
        onCancel={() => setModalVisit6(false)}
        width={900}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
          initialValues={{
            taskId: thetask,
          }}
        >
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item name="id" label="id" hidden={true}>
                <Input />
              </Form.Item>
              <Form.Item name="workOrderInforId" label="工单Id" hidden={true}>
                <Input />
              </Form.Item>
              <Form.Item
                name="workOrderInforCode"
                label="工单编号"
                rules={[{ required: true, message: 'Please input your processCode!' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="生产任务"
                name="taskId"
                rules={[{ required: true, message: '请选择任务!' }]}
              >
                <Select
                  // labelInValue
                  placeholder="请选择任务"
                  onChange={(value) => { }}
                  options={optionsTask}
                  style={{ width: 291 }}
                  disabled
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="异常分类"
                name="errorType"
                rules={[{ required: true, message: '请选择异常分类!' }]}
              >
                <Select
                  placeholder="请选择异常分类"
                  onChange={(value) => { }}
                  options={theerrortype}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="handlingMan"
                label="异常处理人"
                rules={[{ required: true, message: '请输入异常处理人!' }]}
              >
                <Select
                  placeholder="请选择异常处理人"
                  onChange={(value) => {
                    if (value == username) {
                      message.warning('处理人和申报人不能相同');
                      form.setFieldsValue({
                        handlingMan: '',
                      });
                    }
                  }}
                  options={TeamMembername}
                  allowClear={true}
                  showSearch={true}
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={12}>
              <Form.Item
                label="异常优先级"
                name="priority"
                rules={[{ required: true, message: '请选择异常优先级!' }]}
              >
                <Select
                  placeholder="请选择异常优先级"
                  onChange={(value) => { }}
                  options={thepriority}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="deadLinetime"
                label="要求处理时间"
                rules={[{ required: true, message: '请输入要求处理时间!' }]}
              >
                <DatePicker style={{ width: 240 }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={24}>
              <Form.Item label="异常附件" name="file">
                <Upload
                  file-list="fileList"
                  onFilesChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
                  showUploadList={true}
                  beforeUpload={handleBeforeUpload}
                  multiple
                >
                  <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
                    上传文件
                  </Button>
                </Upload>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={[50, 0]}>
            <Col span={24}>
              <Form.Item
                name="errorDes"
                label="问题描述"
              /* rules={[{ required: true, message: '请输入问题描述!' }]} */
              >
                <TextArea rows={3} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      <Modal
        className="lookModal"
        title="检查表执行查看"
        open={lookVisit}
        onOk={keepSubmit}
        onCancel={() => {
          setLookVisit(false);
        }}
        footer={
          <Button type="primary" onClick={keepSubmit}>
            提交
          </Button>
        }
        width={1200}
        destroyOnClose
      >
        <div className="look-title">{lookInfo ? lookInfo.inspectionTask.templateName : '****'}</div>
        <div className="navInfo">
          <div className="navLeft">电柜管家</div>
          <div>项目名称：{lookInfo ? lookInfo.inspectionTask.projectName : '****'} </div>
          <div>项目编号：{lookInfo ? lookInfo.inspectionTask.projectCode : '****'}</div>
          <div>工单编号：{lookInfo ? lookInfo.inspectionTask.wo : '****'}</div>
          <div>操作人：{lookInfo ? lookInfo.inspectionTask.finisher : '****'}</div>
          <div>确认人：{lookInfo ? lookInfo.inspectionTask.inspector : '****'}</div>
        </div>
        <div className="content">
          <Form
            name="wrap"
            labelCol={{ flex: '110px' }}
            labelAlign="left"
            labelWrap
            form={lookForm}
            wrapperCol={{ flex: 1 }}
            colon={false}
          >
            {lookInfo
              ? lookInfo.inspectionItemExList.map((item: any, index: number) => {
                return (
                  <Form.Item
                    key={index}
                    className="look-infos"
                    name={item.id}
                    label={index + 1 + '、' + item.itemName + ':' + item.inspectionMethod}
                  >
                    <Input placeholder="请输入描述内容" onBlur={(e) => onBlur(e, index)} />
                  </Form.Item>
                );
              })
              : ''}
          </Form>
        </div>
      </Modal>
      <Modal
        key={4}
        title={'异常处理'}
        width={1500}
        visible={modalVisit4}
        destroyOnClose
        onCancel={() => {
          setModalVisit4(false);
          actionRef1.current!.reload();
        }}
        footer={[null]}
      >
        <ErrorReport
          errorRecordInfo={errorRecord}
          errorTableList={ErrorTableList}
          workOrderInforCode={recordInfo?.workOrderInforCode}
        />
      </Modal>
      <Modal
        visible={modalVisit3}
        title={formTitle}
        width={1000}
        height={400}
        // onFinish={handleSubmit}
        // modalProps={{
        //   destroyOnClose: true,
        //   onCancel: () => {
        //     setModalVisit(false);
        //     actionRef.current!.reload();
        //   },
        // }}
        onCancel={() => {
          setModalVisit3(false);
        }}
        footer={null} //取消页脚
      >
        <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
          <Descriptions title="" bordered column={2}>
            <Descriptions.Item label="异常分类">
              {errorRecord?.errorType ? errorRecord?.errorType : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="要求处理时间">
              {errorRecord?.deadLine ? errorRecord?.deadLine : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="处理人">
              {errorRecord?.handlingMan ? errorRecord?.handlingMan : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="发布人">
              {errorRecord?.operator ? errorRecord?.operator : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="工单编号">
              {errorRecord?.wo ? errorRecord?.wo : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="优先级">
              {errorRecord?.priority == 1 ? '优先' : errorRecord?.priority == 2 ? '次优先' : '一般'}
            </Descriptions.Item>
            <Descriptions.Item label="异常描述" span={2}>
              {errorRecord?.errorDes ? errorRecord?.errorDes : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="异常附件" span={2}>
              <Row align={'middle'}>
                <Col span={12}>{errorRecord?.fileName ? errorRecord?.fileName : '-'}</Col>
                <Col span={12}>
                  <Button
                    key="download_button"
                    icon={<DownloadOutlined />}
                    disabled={errorRecord?.fileName == null || errorRecord?.fileName == ''}
                    onClick={() => {
                      downloadErrorReportFile({ errorReportId: errorRecord?.id }).then((res) => {
                        const aLink = document.createElement('a');
                        document.body.appendChild(aLink);
                        aLink.style.display = 'none';
                        aLink.href = window.URL.createObjectURL(res);
                        aLink.setAttribute('download', `${errorRecord?.fileName}`);
                        aLink.click();
                        document.body.removeChild(aLink);
                      });
                    }}
                    type="primary"
                  >
                    预览下载
                  </Button>
                </Col>
              </Row>
            </Descriptions.Item>
            <Descriptions.Item label="处理描述" span={2}>
              {errorRecord?.handleDes ? errorRecord?.handleDes : '-'}
            </Descriptions.Item>
          </Descriptions>
          <Row align={'middle'} gutter={[50, 0]}>
            <Col span={12}>
              <div style={{ textAlign: 'center' }}>
                <Button
                  type="primary"
                  disabled={
                    errorRecord?.handleStatus == '1' ||
                    username != handlingname ||
                    errorRecord?.handleStatus == '2'
                  }
                  onClick={() => {
                    setModalVisit2(true);
                  }}
                >
                  去处理
                </Button>
              </div>
            </Col>
            <Col span={12}>
              <div style={{ textAlign: 'center' }}>
                <Button
                  type="primary"
                  disabled={errorRecord?.handleStatus == 2 || username != errorRecord?.operator}
                  onClick={async () => {
                    errorRecord.handleStatus = '2';
                    const errorReportDto = errorRecord;
                    const result = await updateErrorReport(errorReportDto);
                    if (result != null) {
                      message.success('异常已完成');
                    }
                    setModalVisit3(false);
                  }}
                >
                  完成
                </Button>
              </div>
            </Col>
          </Row>
        </Space>
      </Modal>
      {/* 去处理弹窗界面 */}
      <Modal
        title="异常处理"
        visible={modalVisit2}
        onOk={dealwith}
        confirmLoading={confirmLoading2}
        destroyOnClose
        onCancel={() => {
          setModalVisit2(false);
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item
            label="处理描述"
            name="handleDes"
            rules={[{ required: true, message: '请填写处理描述!' }]}
          >
            {/* <Input /> */}
            <TextArea placeholder="请填写处理描述" autoSize={{ minRows: 3, maxRows: 5 }} />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        className="drawingPreviewContainer"
        visible={modalVisit7}
        title="文件预览"
        onCancel={() => {
          setModalVisit7(false);
        }}
        width={1500}
        footer={null}
      >
        <iframe className="drawingPreviewStyle" src={drawingPreview} />
      </Modal>
    </PageHeaderWrapper>
  );
};
export default ProductManufactInforExecute;
